package net.pws.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;

public class IoUtil {
	public static void close(InputStream input) {
		if (input != null) {
			try {
				input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(OutputStream output) {
		if (output != null) {
			try {
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 得到指定文件路径的父目录
	 * 
	 * @param filePath
	 *            绝对路径
	 * @return
	 */
	public static String getFolder(String filePath) { 
		if (filePath == null || filePath.trim().length() == 0) {
			return null;
		}
		int i = filePath.lastIndexOf("/");
		int j = filePath.lastIndexOf("\\");
		int index = i > j ? i : j;
		return filePath.substring(0, index);
	}

	/**
	 * 得到指定文件的文件名
	 * 
	 * @param filePath
	 * @return
	 */
	public static String getFileName(String filePath) {
		if (filePath == null || filePath.trim().length() == 0) {
			return null;
		}
		int i = filePath.lastIndexOf("/");
		int j = filePath.lastIndexOf("\\");
		int index = i > j ? i : j;
		return filePath.substring(index + 1);
	}

	/**
	 * 得到指定文件的扩展名
	 * 
	 * @param filePath
	 * @return
	 */
	public static String getExtendName(String filePath) {
		if (filePath == null || filePath.trim().length() == 0) {
			return null;
		}

		int index = filePath.lastIndexOf(".");
		if (index < 0) {
			return filePath;
		}
		return filePath.substring(index + 1);
	}

	/**
	 * 复制文件
	 * 
	 * @param sourcePath
	 * @param destPath
	 * @throws IOException
	 */
	public static void copy(File sourceFile, String destPath)
			throws IOException {
		File destFile = new File(destPath);
		copy(sourceFile, destFile);
	}

	/**
	 * 复制文件
	 * @param sourceFile
	 * @param destFile
	 * @throws IOException
	 */
	public static void copy(File sourceFile, File destFile) throws IOException {
		int length = 2097152;
		FileInputStream in = new FileInputStream(sourceFile);
		FileOutputStream out = new FileOutputStream(destFile);
		FileChannel inC = in.getChannel();
		FileChannel outC = out.getChannel();
		while (true) {
			if (inC.position() == inC.size()) {
				inC.close();
				outC.close();
				out.close();
				in.close();
				return;
			}
			if ((inC.size() - inC.position()) < 20971520)
				length = (int) (inC.size() - inC.position());
			else
				length = 20971520;
			inC.transferTo(inC.position(), length, outC);
			inC.position(inC.position() + length);
		}
	}
	
	public static void main(String[] args){
	    String name = "e622eec8-541f-45dd-a3c6-22440fa0c4c1.jpg";
	    System.out.println(getExtendName(name));
	}
}
